<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="流程编码" prop="flowCode">
        <el-select v-model="queryParams.type" placeholder="请选择流程类型" clearable>
          <el-option
            v-for="dict in flow_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="流程类别" prop="category">
        <el-select
          v-model="queryParams.category"
        >
          <el-option
            v-for="dict in work_flow"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="流程名称" prop="flowName">
        <el-input
          v-model="queryParams.flowName"
          placeholder="请输入流程名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="流程版本" prop="version">
        <el-input
          v-model="queryParams.version"
          placeholder="请输入流程版本"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['flow:definition:add']"
        >新增</el-button>
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="small"
          @click="handleImport"
          v-hasPermi="['flow:definition:importDefinition']"
        >导入流程定义</el-button>
      </el-col>
      <RightToolbar :showSearch="showSearch" @queryTable="getList"></RightToolbar>
    </el-row>

    <el-table v-loading="loading" :data="definitionList" @selection-change="handleSelectionChange"  @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center" fixed />
      <el-table-column label="序号" width="150" align="center" key="id" prop="id">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="流程编码" align="center" prop="flowCode" width="250" sortable="custom"  :show-overflow-tooltip="true"/>
      <el-table-column label="流程名称" align="center" prop="flowName" sortable="custom" width="250" :show-overflow-tooltip="true"/>
      <el-table-column label="流程版本" align="center" prop="version" width="150" sortable="custom" :show-overflow-tooltip="true">
        <template #default="scope">
          <el-tag>{{scope.row.version}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="流程类别" align="center" prop="category" :show-overflow-tooltip="true">
        <template #default="scope">
          <dict-tag :options="work_flow" :value="scope.row.category"/>
        </template>
      </el-table-column>
      <el-table-column label="是否发布" align="center" prop="isPublish" width="140" sortable="custom" :show-overflow-tooltip="true">
        <template #default="scope">
          <dict-tag :options="dict.type.is_publish" :value="scope.row.isPublish"/>
        </template>
      </el-table-column>
      <el-table-column label="激活状态" align="center" prop="activityStatus" width="140" sortable="custom" :show-overflow-tooltip="true">
        <template #default="scope">
          <dict-tag :options="dict.type.activity_status" :value="scope.row.activityStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" sortable="custom" :sort-orders="['descending', 'ascending']" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="350" fixed="right" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="small"
            type="text"
            @click="handleDesign(scope.row.id, scope.row.isPublish)"
            v-hasPermi="['flow:definition:queryDesign']"
          >流程设计</el-button>
          <el-button
            size="small"
            type="text"
            v-if="scope.row.isPublish === 0"
            @click="handlePublish(scope.row.id)"
            v-hasPermi="['flow:definition:publish']"
          >发布</el-button>
          <el-button
            size="small"
            type="text"
            v-if="scope.row.isPublish === 1"
            @click="handleUpPublish(scope.row.id)"
            v-hasPermi="['flow:definition:upPublish']"
          >取消发布</el-button>
          <el-button
            size="small"
            type="text"
            v-if="scope.row.activityStatus === 0"
            @click="toActive(scope.row.id)"
          >激活</el-button>
          <el-button
            size="small"
            type="text"
            v-if="scope.row.activityStatus === 1"
            @click="toUnActive(scope.row.id)"
          >挂起</el-button>
          <el-button
            size="small"
            type="text"
            @click="handleCopyDef(scope.row.id)"
            v-hasPermi="['flow:definition:upPublish']"
          >复制流程</el-button>
          <el-button
            size="small"
            type="text"
            @click="handleExport(scope.row)"
            v-hasPermi="['flow:definition:exportDefinition']"
          >导出流程</el-button>
          <el-button
            size="small"
            type="text"
            v-if="scope.row.isPublish === 0"
            @click="handleDelete(scope.row)"
            v-hasPermi="['flow:definition:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        multiple
        :limit="20"
        accept=".json"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center">
          <span>仅允许导入json格式文件。</span>
        </div>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="流程图" v-model="flowChart" width="80%">
      <img :src="imgUrl" width="100%" style="margin:0 auto"/>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { UploadFilled } from '@element-plus/icons-vue'
import {
  listDefinition,
  delDefinition,
  publish,
  unPublish,
  copyDef,
  active as apiActive,
  unActive as apiUnActive
} from '@/api/flow/definition'
import { getToken } from '@/utils/auth'
import DictTag from "@/components/DictTag/index.vue";
import {useDict} from "@/utils/dict";

const { proxy } = getCurrentInstance();
const router = useRouter();
const {work_flow,flow_type}= proxy.useDict("work_flow","flow_type");
// 数据定义
const loading = ref(true);
const imgUrl = ref("");
const flowChart = ref(false);
const uniqueId = ref("");
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const definitionList = ref([]);
const queryFormRef = ref();
const uploadRef = ref();

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  type: null,
  flowName: null,
  category: null,
  version: null,
  orderByColumn: undefined,
  isAsc: undefined

});

const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  headers: { Authorization: "Bearer " + getToken() },
  url: "/work-flow/flow/definition/importDefinition"
});

const dict = reactive({
  type: {
    is_publish: [],
    activity_status: []
  }
});

// 生命周期钩子
onMounted(() => {
  getList();
  // 初始化字典数据（根据实际项目调整）
  initDict();
});

// 方法定义
function getList() {
  loading.value = true;
  listDefinition(queryParams).then(response => {
    definitionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

function resetQuery() {
  proxy.resetForm("queryFormRef");
  handleQuery();
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

function handleAdd() {
  const params = { disabled: false, pageNum: queryParams.pageNum };
  router.push({
    path: '/flow/flow-design/index',
    query: params
  });
}

function handleDesign(id, isPublish) {
  const params = { disabled: isPublish === 1, pageNum: queryParams.pageNum };
  router.push({
    path: `/flow/flow-design/index/${id}`,
    query: params
  });
}

function handlePublish(id) {
  proxy.$modal.confirm('是否确认发布流程定义编号为"' + id + '"的数据项？').then(() => {
    return publish(id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("发布成功");
  }).catch(() => {});
}

function handleUpPublish(id) {
  proxy.$modal.confirm('是否确认取消发布流程定义编号为"' + id + '"的数据项？').then(() => {
    return unPublish(id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("取消成功");
  }).catch(() => {});
}

function handleDelete(row) {
  const deleteIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除流程定义编号为"' + deleteIds + '"的数据项？').then(() => {
    return delDefinition(deleteIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

function handleCopyDef(id) {
  proxy.$modal.confirm('是否确认复制流程定义编号为"' + id + '"的数据项？').then(() => {
    return copyDef(id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("复制成功");
  }).catch(() => {});
}

function handleImport() {
  upload.title = "导入流程定义";
  upload.open = true;
}

function handleExport(row) {
  proxy.download('/work-flow/flow/definition/exportDefinition/' + row.id, {
    ...queryParams
  }, row.flowCode + '_' + row.version + '.json')
}

function handleFileUploadProgress(event, file, fileList) {
  upload.isUploading = true;
}

function handleFileSuccess(response, file, fileList) {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value.clearFiles();
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
}

function submitFileForm() {
  uploadRef.value.submit();
}

function handleSortChange(column) {
  if (column.prop) {
    queryParams.orderByColumn = column.prop;
    queryParams.isAsc = column.order === 'ascending' ? 'asc' : 'desc';
    getList();
  }
}

function toActive(id) {
  proxy.$modal.confirm('是否确认激活流程定义编号为"' + id + '"的数据项？').then(() => {
    return apiActive(id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("激活成功");
  }).catch(() => {});
}

function toUnActive(id) {
  proxy.$modal.confirm('是否确认挂起流程定义编号为"' + id + '"的数据项？').then(() => {
    return apiUnActive(id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("挂起成功");
  }).catch(() => {});
}

function parseTime(time) {
  // 这里实现时间格式化逻辑
  return proxy.parseTime(time);
}

function initDict() {
  // 这里初始化字典数据（根据实际项目调整）
  dict.type.is_publish = [
    { label: '未发布', value: '0' },
    { label: '已发布', value: '1' }
  ];
  dict.type.activity_status = [
    { label: '挂起', value: '0' },
    { label: '激活', value: '1' }
  ];
}
</script>

<style scoped>
/* 样式保持不变 */
</style>
